package com.example.demokaptcha.controller;

import com.example.service.TbBookService;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * <p>
 * Index
 * </p>
 *
 * @author ross zhang
 * @version 1.0
 * @since 2022/4/10 19:33
 */
@RestController
public class IndexController {
    @Autowired
    private TbBookService tbBookService;
    @Autowired
    private Producer kaptchaProducer;

    @GetMapping
    public ModelAndView index(ModelAndView modelAndView) {
//        List<TbBook> list = this.tbBookService.list();
        modelAndView.addObject("success", "我是Freemarker页面");
//        modelAndView.addObject("listBook", list);
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @GetMapping(value = "/kaptcha")
    public void getKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception{
        byte[] captcha = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {
            // 将生成的验证码保存在session中
            String createText = this.kaptchaProducer.createText();
            System.out.println(createText);
            request.getSession().setAttribute("rightCode", createText);
            BufferedImage bi = this.kaptchaProducer.createImage(createText);
            System.out.println(bi);
            ImageIO.write(bi, "jpg", out);
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        captcha = out.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream sout = response.getOutputStream();
        sout.write(captcha);
        sout.flush();
        sout.close();
    }
}
